package crossover;

import java.util.ArrayList;
import java.util.Random;

import model.Chromosome;

public class OX1 extends Crossover {
	Random rand = new Random();

	public OX1(double crossoverRate) {
		this.crossoverRate = crossoverRate;
	}

	@Override
	public Chromosome[] crossover(Chromosome[] parents) {
		int size = parents[0].getChromosome().size();
		double rate = rand.nextDouble() * 100;
//		int index1 = rand.nextInt(size);
		int index1 = 0;
		int index2 = rand.nextInt(size);
		// swap
		if (index1 > index2) {
			int index3 = index1;
			index1 = index2;
			index2 = index3;

		}
		if (rate > crossoverRate) {

			ArrayList<Integer> ch1 = new ArrayList<Integer>(), ch2 = new ArrayList<Integer>();
			for (int i = index1; i < index2; ++i) {
				ch1.add(parents[0].getChromosome().get(i));
				ch2.add(parents[1].getChromosome().get(i));
			}
			ArrayList<Integer> removed1 = removeExist(
					parents[1].getChromosome(), ch1);
			ArrayList<Integer> removed2 = removeExist(
					parents[0].getChromosome(), ch2);
			int j = 0;
			for (int i = index2; i < size; i++, j++) {
				ch1.add(removed1.get(j));
				ch2.add(removed2.get(j));
			}
			
			for(int i=0;i<index1;i++,j++){
				ch1.add(0,removed1.get(j));
				ch2.add(0,removed2.get(j));
				
			}
			Chromosome[] child = { new Chromosome(ch1), new Chromosome(ch2) };
			return child;
		} else
			return parents;

	}

	@Override
	public String toString() {
		return "OX1";
	}

	protected boolean existNumInCh(ArrayList<Integer> ch2, int num) {
		for (Integer integer : ch2) {
			if (integer.intValue() == num)
				return true;
		}
		return false;
	}

	protected ArrayList<Integer> removeExist(ArrayList<Integer> parent,
			ArrayList<Integer> exist) {
		// parent\exist=removed
		ArrayList<Integer> removed = new ArrayList<Integer>();
		for (Integer integer : parent) {
			if (!existNumInCh(exist, integer))
				removed.add(integer);

		}
		return removed;
	}

}
